#!/bin/bash -xe

pushd $HOME/workspace/CoCo/deployment/samples

export kbs_namespace="trustee-operator-system"
export kbs_deploy="trustee-deployment"
export kbs_pod_ip_addr="$(kubectl get pods -n $kbs_namespace -o wide | \
  grep $kbs_deploy | \
  sed "s/^.* \([0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\) .*$/\1/g")"
export kbs_resource_dir="/opt/confidential-containers/kbs/repository"
export KBS_KEY_PATH="default/containers/auth"

your_image="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
your_credential_username="BBBBBBBBBBBBBBBBBBBBBB"
your_credential_password="CCCCCCCCCCCCCCCCCCCCCC"

export auth_conf_file=auth-pod.json
export pod_yaml=auth.yaml
export pod_name="nginx"
export pod_container_image="${your_image}"
export pod_runtimeclass="kata-qemu-csv3"

export AUTHENTICATED_IMAGE="${your_image}"
export AUTHENTICATED_IMAGE_NAMESPACE="$(echo "$AUTHENTICATED_IMAGE" | cut -d':' -f1)"
export AUTHENTICATED_IMAGE_USER="${your_credential_username}"
export AUTHENTICATED_IMAGE_PASSWORD="${your_credential_password}"

export K8S_SECRET_NAME="cococred"

# 生成credential文件
cat <<EOF> $auth_conf_file
{
        "auths": {
                "${AUTHENTICATED_IMAGE_NAMESPACE}": {
                        "auth": "$(echo ${AUTHENTICATED_IMAGE_USER}:$AUTHENTICATED_IMAGE_PASSWORD} | base64 -w 0)"
                }
        }
}
EOF

# 将credential文件上传到KBS存储目录
kubectl exec deploy/$kbs_deploy \
    -c kbs -n $kbs_namespace \
    -- mkdir -p "$kbs_resource_dir/$(dirname "$KBS_KEY_PATH")"
  cat $auth_conf_file | kubectl exec -i deploy/$kbs_deploy \
    -c kbs -n $kbs_namespace \
    -- tee "$kbs_resource_dir/${KBS_KEY_PATH}" > /dev/null

# 创建一个crecential的secret，机密容器启动之前，containerd的nydus-snapshotter需要该信息
kubectl delete secret ${K8S_SECRET_NAME} || true  ####FIXME
kubectl create secret docker-registry "${K8S_SECRET_NAME}" \
  --docker-server="https://${AUTHENTICATED_IMAGE_NAMESPACE}" \
  --docker-username="${AUTHENTICATED_IMAGE_USER}" \
  --docker-password="${AUTHENTICATED_IMAGE_PASSWORD}"

# 设置pod的yaml文件
cp $pod_yaml.template $pod_yaml
sed -i "s!MARK_KBS_KEY_PATH!${KBS_KEY_PATH}!g" $pod_yaml
sed -i "s!MARK_KBS_POD_IP_ADDR!$kbs_pod_ip_addr!g" $pod_yaml
sed -i "s!MARK_POD_NAME!${pod_name}!g" $pod_yaml
sed -i "s!MARK_POD_CONTAINER_IMAGE!${pod_container_image}!g" $pod_yaml
sed -i "s!MARK_POD_RUNTIMECLASS!${pod_runtimeclass}!g" $pod_yaml
sed -i "s!MARK_SECRET_NAME!${K8S_SECRET_NAME}!g" $pod_yaml

kubectl delete -f $pod_yaml || true ####FIXME
kubectl apply -f $pod_yaml

pushd ../tools/measurement/
measure=$(./csv-calc-measurement.sh csv3 | \
  grep "MEASUREMENT => " | sed "s/MEASUREMENT => //" | \
  sed 's/^[[:space:]]*//')
echo $measure
popd
